package start.spring.basic.util.common;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * ****************************************************************************
 * java操作cookie工具类
 *
 * @author(作者)：xuyongyun	
 * @author(复审人)：	Administrator 2016-8-20
 * @version(版本)1.0
 * @since 1.0
 ******************************************************************************
 */

public class CookieUtil {
	
	/**
	 * 添加一个cookie值
	 *	
	 * @param response http相应
	 * @param name cookie的名称
	 * @param value cookie的值
	 * @param maxAge cookie的过期时间，0时设置为浏览器关闭cookie失效
	 * @param flag cookie的是否允许js读取标志，true不允许，false允许
	 * @since           1.0
	 */
	public static void addCookie(HttpServletResponse response,String name,String value,int maxAge,boolean flag){

		 StringBuilder builder = new StringBuilder();  
	     builder.append(name+"=" + value + ";");
		 builder.append("Path=/;"); 
		 //不允许js读取cookies
		 if(flag==true){
	    	 builder.append("HTTPOnly;");
	     }
		 if(maxAge>0){
		     builder.append("Max-Age=" + maxAge);
		 }
		 response.addHeader("Set-Cookie", builder.toString()); 

	}
	
	/**
	 * 读取cookie的值
	 *	
	 * @param request http请求
	 * @param name cookie的名称
	 * @return
	 * @since           1.0
	 */
	public static String getCookie(HttpServletRequest request,String name){
		String value = "";
		Cookie[] cookies = request.getCookies();
		if(cookies!=null&&cookies.length>0){
			for(int i=0;i<cookies.length;i++){
				if(cookies[i].getName().equals(name)){
					value = cookies[i].getValue();
					break;
				}else{
					continue;
				}
			}
		}
		return value;
	}
	
	/**
	 * 根据名称删除某个cookie
	 *	
	 * @param request
	 * @param response
	 * @param name 待删除的cookie名称
	 * @return
	 * @since           1.0
	 */
	public static String deleteCookie(HttpServletRequest request, HttpServletResponse response, String name){
		String value = "";
		Cookie[] cookies = request.getCookies();
		if(cookies!=null&&cookies.length>0){
			for(int i=0;i<cookies.length;i++){
				if(cookies[i].getName().equals(name)){
					Cookie cookie = new Cookie(name, "");  
		            cookie.setMaxAge(1);
		            //根据你创建cookie的路径进行填写
		            cookie.setPath("/");
		            response.addCookie(cookie);  
					break;
				}else{
					continue;
				}
			}
		}
		return value;
	}
	
	/**
	 * 清空cookie
	 *	
	 * @param request
	 * @param response
	 * @return
	 * @since           1.0
	 */
	public static HttpServletResponse clearCookie(HttpServletRequest request, HttpServletResponse response){
		Cookie[] cookies = request.getCookies();  
		try{     
			for(int i=0;i<cookies.length;i++){  
	            Cookie cookie = new Cookie(cookies[i].getName(), "");  
	            cookie.setMaxAge(1);
	            //根据你创建cookie的路径进行填写 
	            cookie.setPath("/");     
	            response.addCookie(cookie);  
            }
	    }catch(Exception ex){
	           
	    }
	    return response;
	}
	
}
